package com.goldgov.code.web;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.goldgov.code.meta.AuthorInfo;
import com.goldgov.code.meta.FieldInfo;
import com.goldgov.code.meta.ModuleInfo;
import com.goldgov.code.meta.semantics.impl.PorjectSemanticsTranslate;
import com.goldgov.code.meta.source.MetaSource;
import com.goldgov.code.meta.source.impl.JdbcMetaSource;
import com.goldgov.code.meta.source.impl.SqlMetaSource;
import com.goldgov.code.service.FieldService;
import com.goldgov.code.service.Log;
import com.goldgov.code.service.LogService;
import com.goldgov.code.service.ModuleService;
import com.goldgov.code.service.User;
import com.goldgov.code.template.Group;
import com.goldgov.code.template.Layout;
import com.goldgov.code.template.ParamKeyName;
import com.goldgov.code.template.impl.BeanLayout;
import com.goldgov.code.template.impl.DaoLayout;
import com.goldgov.code.template.impl.PageLayout;
import com.goldgov.code.template.impl.ServiceLayout;
import com.goldgov.code.template.impl.WebLayout;
import com.goldgov.code.utils.FreemarkerUtils;
import com.goldgov.jdbc.service.JdbcConfigService;
import com.goldgov.k8s.Environment;

import freemarker.template.Template;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/code")
public class CodeController {

	@Autowired
	private ModuleService moduleService;
	
	@Autowired
	private FieldService fieldService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private JdbcConfigService jdbcConfigService;
	
	@Autowired
	private DataSource dataSource;
	
	@Value("${source-code.gen-path}")
	private String genPath;
	
	@Value("${source-code.template-path}")
	private String templatePath;
	
	@PostMapping("/sqlFile")
	@ApiOperation(value = "导入模块信息")
	public String importModule(@ApiParam(value = "上传的SQL脚本文件", required = true) @RequestParam("sqlFile") MultipartFile sqlFile,@RequestParam("projectID") String projectID,HttpServletRequest request){
		User user = getUser(request);
		
		int importCount = 0;
		String mName = null;
		try (InputStream inputStream = sqlFile.getInputStream()){
			MetaSource sqlMetaSource = new SqlMetaSource(inputStream);
			ModuleInfo[] resolve = sqlMetaSource.resolve();
			for (ModuleInfo moduleInfo : resolve) {
				moduleService.addModule(moduleInfo);
				importCount++;
				if(mName == null) {
					mName = moduleInfo.getExplain();
				}
			}
		} catch (IOException e) {
			throw new RuntimeException("读取上传的SQL文件出现IO错误",e);
		}
		Log log = new Log(Log.LOG_TYPE_IMPORT_MODULE_BY_SQL);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("通过文件方式导入了" + mName + "模块" + (importCount > 1 ? "等" + importCount + "个模块" : ""));
		logService.addLog(log);
		
		return "SUCCESS";
	}
	
	@PostMapping("/sqlScript")
	@ApiOperation(value = "导入模块信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sqlScript", value = "创建数据表的SQL脚本")
			})
	public List<String> importModule(@RequestParam("sqlScript") String sqlScript,@RequestParam("projectID") String projectID,@RequestParam(name="ignorePrefix",required=false) String prefix,@RequestParam("translate")boolean translate,HttpServletRequest request){
		User user = getUser(request);
		
		MetaSource sqlMetaSource = new SqlMetaSource(sqlScript);
		if(translate) {
			sqlMetaSource.setSemanticsTranslate(new PorjectSemanticsTranslate(dataSource,projectID));
		}
		ModuleInfo[] resolve = sqlMetaSource.resolve(prefix);
		List<String> ids = new ArrayList<>();
		
		String mName = null;
		
		for (ModuleInfo moduleInfo : resolve) {
			moduleInfo.setProjectID(projectID);
			moduleService.addModule(moduleInfo);
			ids.add(moduleInfo.getModuleID());
			if(mName == null) {
				mName = moduleInfo.getExplain();
			}
		}
		Log log = new Log(Log.LOG_TYPE_IMPORT_MODULE_BY_SQL);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("导入了" + mName + "模块" + (ids.size() > 1 ? "等" + ids.size() + "个模块" : ""));
		logService.addLog(log);
		
		return ids;
	}
	
	@PostMapping("/jdbc")
	public List<String> jdbcImportModule(@RequestParam("configID") String configID,@RequestParam("tableName") String[] tableName,@RequestParam("projectID") String projectID,@RequestParam(name="ignorePrefix",required=false) String prefix,@RequestParam("translate")boolean translate, HttpServletRequest request){
		User user = getUser(request);
		
		JdbcMetaSource sqlMetaSource = new JdbcMetaSource(jdbcConfigService,configID,tableName);
		if(translate) {
			sqlMetaSource.setSemanticsTranslate(new PorjectSemanticsTranslate(dataSource,projectID));
		}
		ModuleInfo[] resolve = sqlMetaSource.resolve(prefix);
		List<String> ids = new ArrayList<>();
		
		String mName = null;
		
		for (ModuleInfo moduleInfo : resolve) {
			moduleInfo.setProjectID(projectID);
			moduleService.addModule(moduleInfo);
			ids.add(moduleInfo.getModuleID());
			if(mName == null) {
				mName = moduleInfo.getName();
			}
		}
		Log log = new Log(Log.LOG_TYPE_IMPORT_MODULE_BY_JDBC);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("导入了" + mName + "模块" + (ids.size() > 1 ? "等" + ids.size() + "个模块" : ""));
		logService.addLog(log);
		
		return ids;
	}
	
	@PostMapping("/module")
	@ApiOperation(value = "添加模块信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "packageName", value = "模块包名"),
			@ApiImplicitParam(name = "name", value = "模块对象名"),
			@ApiImplicitParam(name = "explain", value = "模块说明"),
			@ApiImplicitParam(name = "tableName", value = "模块表名"),
			})
	public String addModule(@ApiIgnore ModuleInfo module, HttpServletRequest request){
		User user = getUser(request);
		
		moduleService.addModule(module);
		
		Log log = new Log(Log.LOG_TYPE_ADD_MODULE);
		log.setUser(user);
		log.setProjectID(module.getProjectID());
		log.setLogContent("添加了" + module.getExplain() + "模块");
		logService.addLog(log);
        return "SUCCESS";
	}
	
	@PostMapping("/relation")
	@ApiOperation(value = "模块关联")
	public String relationModule(@RequestParam("primaryModuleID") String primaryModuleID,@RequestParam("subModuleID") String subModuleID){
		moduleService.addRelationModule(primaryModuleID, subModuleID);
		return "SUCCESS";
	}
	
	@GetMapping("/module/project/{projectID}")
	public List<ModuleInfo> listModule(@PathVariable("projectID") String projectID){
		List<ModuleInfo> listModule = moduleService.listModule(projectID);
        return listModule;
	}
	
	@DeleteMapping("/module")
	public String deleteModule(@RequestParam("moduleIDs") String[] ids,@RequestParam("projectID") String projectID,HttpServletRequest request){
		User user = getUser(request);
		
		moduleService.deleteModule(ids);
		
		Log log = new Log(Log.LOG_TYPE_REMOVE_MODULE);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("删除了" + ids.length + "个模块");
		logService.addLog(log);
        return "SUCCESS";
	}
	
	@PutMapping("/module")
	@ApiOperation(value = "修改模块信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "packageName", value = "模块包名"),
		@ApiImplicitParam(name = "name", value = "模块对象名"),
		@ApiImplicitParam(name = "explain", value = "模块说明"),
		@ApiImplicitParam(name = "tableName", value = "模块表名"),
		})
	public String updateModule(@ApiIgnore ModuleInfo module){
		moduleService.updateModule(module);
        return "SUCCESS";
	}
	
	@GetMapping("/module/{moduleID}")
	public ModuleInfo getModule(@PathVariable("moduleID") String moduleID){
		ModuleInfo moduleInfo = moduleService.getModule(moduleID);
        return moduleInfo;
	}
	
	@GetMapping("/field")
	public List<FieldInfo> listField(@RequestParam("moduleID") String moduleID){
		List<FieldInfo> listModule = fieldService.listField(moduleID);
        return listModule;
	}
	
	@GetMapping("/field/{fieldID}")
	public FieldInfo getField(@PathVariable("fieldID") String fieldID){
        return fieldService.getField(fieldID);
	}
	
	@PutMapping("/field")
	public String updateField(FieldInfo field){
        fieldService.updateField(field);
        return "SUCCESS";
	}
	
	@PutMapping("/field/listField/{fieldID}")
	public String updateListField(@PathVariable("fieldID") String fieldID, @RequestParam("isTrue") boolean isTrue){
        fieldService.updateConstraintList(fieldID,isTrue);
        return "SUCCESS";
	}
	
	@PutMapping("/field/required/{fieldID}")
	public String updateFieldRequired(@PathVariable("fieldID") String fieldID, @RequestParam("isTrue") boolean isTrue){
        fieldService.updateConstraintRequired(fieldID,isTrue);
        return "SUCCESS";
	}
	
	@PutMapping("/field/query/{fieldID}")
	public String updateFieldQueryType(@PathVariable("fieldID") String fieldID, @RequestParam(name="queryType",required=false) String queryType){
        fieldService.updateConstraintQueryType(fieldID,queryType);
        return "SUCCESS";
	}
	
	@PostMapping("/field")
	public String addField(FieldInfo field){
        fieldService.addField(field);
        return "SUCCESS";
	}
	
	@DeleteMapping("/field")
	public void deleteField(@RequestParam("fieldIDs")String[] fieldIDs){
        fieldService.deleteField(fieldIDs);
	}
	
	@GetMapping("/k8sConfig")
	public void exportK8sConfig(HttpServletRequest request,HttpServletResponse response) {
		User user = getUser(request);
		File file = new File(genPath+File.separator+user.getUserID());
		
		if(file.exists() && file.isDirectory()) {
			delete(file);
		}
		String projectName = request.getParameter("name");
		String projectID = request.getParameter("projectID");
		
		String projectCode = request.getParameter("code");
		String serviceName = request.getParameter("serviceName");
		String deliverPort = request.getParameter("deliverPort");
		String deliverDebugPort = request.getParameter("deliverDebugPort");
		String devPort = request.getParameter("devPort");
		String devDebugPort = request.getParameter("devDebugPort");
		String integratePort = request.getParameter("integratePort");
		String integrateDebugPort = request.getParameter("integrateDebugPort");
		
		String exportType = request.getParameter("exportType");
		String gitHome = request.getParameter("gitHome");
		String frontendType = request.getParameter("frontendType");
		
		Map<String,Object> paramMap = new HashMap<>();
//		projectCode = projectCode.toLowerCase().equals("sx") || projectCode.toLowerCase().equals("klx")? "ms":projectCode;
		paramMap.put("project", request.getParameter("code"));
		paramMap.put("projectName", projectCode);
		paramMap.put("serviceName", serviceName);
		paramMap.put("repository", "file://../" + projectCode + "-" + serviceName);
		paramMap.put("deliver", new Environment(Integer.parseInt(deliverPort),Integer.parseInt(deliverDebugPort)));
		paramMap.put("dev", new Environment(Integer.parseInt(devPort),Integer.parseInt(devDebugPort)));
		paramMap.put("integrate", new Environment(Integer.parseInt(integratePort),Integer.parseInt(integrateDebugPort)));
		paramMap.put("gitHome", gitHome);//git首页
		paramMap.put("frontendType", frontendType);//admin//集成环境，web端口，调试端口
		
		File templateFile = new File(templatePath,"k8s" + File.separator + exportType);
		FreemarkerUtils.init(templateFile);
		configGen(templateFile,"",file,paramMap);
		
		Log log = new Log(Log.LOG_TYPE_CONFIG_EXPORT_K8S_STANDARD);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("导出K8S项目标准配置文件："+projectName);
		logService.addLog(log);
		
		try {
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameEncoding(projectName+".zip",request) + "\"");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			makeZip(file,response.getOutputStream());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@GetMapping("/project")
	public void exportProject(@RequestParam("packageName") String packageName,@RequestParam("exportType") int exportType,@RequestParam("moduleID") String[] moduleIDs,@RequestParam("themeStyle") String themeStyle,@RequestParam(name="requestPrefix",required=false) String requestPrefix,HttpServletRequest request,HttpServletResponse response) {
		User user = getUser(request);
		File file = new File(genPath+File.separator+user.getUserID());
		
		if(file.exists() && file.isDirectory()) {
			delete(file);
		}
		
		
		Map<String,Object> paramMap = new HashMap<>();

		String projectID = request.getParameter("projectID");
		String projectCode = request.getParameter("projectCode");
		String projectName = request.getParameter("projectName");
		String serviceName = request.getParameter("serviceName");
		
		
		file = new File(file,projectCode);
		
		paramMap.put("projectID", projectID);
		paramMap.put("projectCode", projectCode);
		paramMap.put("projectName", serviceName);//此处不是BUG，由于之前模版将projectName定义为了项目编码，因此为了保证兼容，此处也放置了编码值
		paramMap.put("packageName", packageName);
		paramMap.put("userName", user.getName());
		paramMap.put("serviceName", serviceName);
		
		if(serviceName != null && projectCode != null) {
			paramMap.put("artifactId", projectCode + "-" + serviceName);
		}
		
		List<ModuleInfo> moduleList = new ArrayList<>();
		
		for (int i = 0; i < moduleIDs.length; i++) {
			String mid = moduleIDs[i];
			ModuleInfo module = moduleService.getModule(mid);
			File outPath = new File(file,serviceName + "-" + module.getName().toLowerCase() + File.separator + "src" + File.separator + "main" + File.separator + "java");
			genModuleFiles(outPath,packageName,exportType,new String[] {mid},themeStyle,requestPrefix,request);
			moduleList.add(module);
		}
		paramMap.put("moduleList", moduleList);
		if(requestPrefix != null) {
			if(!requestPrefix.startsWith("/")) {
				requestPrefix = "/" + requestPrefix;
			}
			if(requestPrefix.endsWith("/")) {
				requestPrefix = requestPrefix.substring(0,requestPrefix.length()-1);
			}
			paramMap.put(ParamKeyName.REQUEST_PREFIX, requestPrefix);
		}
		
		File templateFile = new File(templatePath,"project" + File.separator + "main");
		FreemarkerUtils.init(templateFile);
		configGen(templateFile,"",file,paramMap);
		
		File outPath = new File(file,serviceName + "-services" + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + StringUtils.replace(packageName, ".", File.separator));
		outPath.mkdirs();
		templateFile = new File(templatePath,"project" + File.separator + "application");
		FreemarkerUtils.init(templateFile);
		configGen(templateFile,"",outPath,paramMap);
		
		templateFile = new File(templatePath,"project" + File.separator + "module");
		FreemarkerUtils.init(templateFile);
		for (ModuleInfo moduleInfo : moduleList) {
			paramMap.put("moduleName", moduleInfo.getName().toLowerCase());
			configGen(templateFile,"",new File(file,serviceName + "-" + moduleInfo.getName().toLowerCase()),paramMap);
		}
		
		Log log = new Log(Log.LOG_TYPE_PROJECT_EXPORT);
		log.setUser(user);
		log.setProjectID(projectID);
		log.setLogContent("导出项目结构");
		logService.addLog(log);
		
		try {
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameEncoding(projectName+"项目结构.zip",request) + "\"");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			makeZip(file.getParentFile(),response.getOutputStream());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void configGen(File templatePath,String path,File outputDir,Map<String,Object> dataMap) {
		File[] listFiles = templatePath.listFiles();
		for (int i = 0; i < listFiles.length; i++) {
			File file = listFiles[i];
			String templateName = file.getName();
			if(templateName != null) {
				templateName = path + "/" + templateName;
			}
			if(file.isDirectory()) {
				String name = file.getName();
				name = name.replaceAll("__serviceName__", ""+dataMap.get("serviceName"));
				name = name.replaceAll("__projectName__", ""+dataMap.get("projectName"));
				File oPath = new File(outputDir,name);
				oPath.mkdirs();
				configGen(file,templateName,oPath,dataMap);
			}else {
				Template template = FreemarkerUtils.getTemplate(templateName);
				FileWriter fileWriter;
				try {
					fileWriter = new FileWriter(outputDir + File.separator + file.getName());
					template.process(dataMap, fileWriter);
				} catch (Exception e) {
					throw new RuntimeException("导出模版时出现错误",e);
				}
			}
			
		}
	}
	
	@GetMapping("/gen")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "packageName", value = "模块包名"),
		@ApiImplicitParam(name = "moduleIDs", value = "模块ID", allowMultiple = true)
		})
	public void codeGen(@RequestParam("packageName") String packageName,@RequestParam("exportType") int exportType,@RequestParam("moduleID") String[] moduleIDs,@RequestParam("themeStyle") String themeStyle,@RequestParam(name="requestPrefix",required=false) String requestPrefix,HttpServletRequest request,HttpServletResponse response){

		User user = getUser(request);
		
		ModuleInfo module = moduleService.getModule(moduleIDs[0]);
		File file = new File(genPath+File.separator+user.getUserID());
		
		if(file.exists() && file.isDirectory()) {
			delete(file);
		}
		
		String exportFileName = module.getExplain();
		if(moduleIDs.length > 1) {
			exportFileName += "等" + moduleIDs.length + "个模块";
		}
		exportFileName += "源码.zip";
		
		genModuleFiles(file,packageName,exportType,moduleIDs,themeStyle,requestPrefix,request);
		
		Log log = new Log(Log.LOG_TYPE_CODE_EXPORT);
		log.setUser(user);
		log.setProjectID(module.getProjectID());
		log.setLogContent("导出了模块："+module.getName());
		logService.addLog(log);
		
		try {
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameEncoding(exportFileName,request) + "\"");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			makeZip(file,response.getOutputStream());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void genModuleFiles(File file,String packageName,int exportType,String[] moduleIDs,String themeStyle,String requestPrefix,HttpServletRequest request) {
		User user = getUser(request);
		
		Group defaultGroup = new Group();
		BeanLayout beanLayout = new BeanLayout();
		DaoLayout daoLayout = new DaoLayout();
		ServiceLayout serviceLayout = new ServiceLayout();
		WebLayout webLayout = new WebLayout();
		
		
		Map<String,Object> paramMap = new HashMap<>();
		
		List<Layout> layoutList = new ArrayList<>();
		if((exportType & 1) > 0) {
			//TODO 项目架构
		}
		if((exportType & 2) > 0) {
			//CODE
			layoutList.add(beanLayout);
			layoutList.add(daoLayout);
			layoutList.add(serviceLayout);
			layoutList.add(webLayout);
		}
		if((exportType & 4) > 0) {
			//PAGE
//			PageLayout pageLayout = new PageLayout();
////			if(!pageStyleLegalCheck(themeStyle)) {
//			if(themeStyle == null || "".equals(themeStyle)) {
//				themeStyle = "1";
//			}
//			pageLayout.setTemplatePath("page/" + themeStyle);
//			layoutList.add(pageLayout);
			paramMap.put(ParamKeyName.THEME_STYLE, themeStyle);
		}
		boolean expDefaultFields = false;
		if((exportType & 8) > 0) {
			//DEFAULT FIELDS
			expDefaultFields = true;
		}
		
		boolean expLogicDelete = false;
		if((exportType & 16) > 0) {
			//LOGIC DELETE
			expLogicDelete = true;
		}

		defaultGroup.setLayouts(layoutList.toArray(new Layout[layoutList.size()]));

		//EXT FIELDS
		paramMap.put(ParamKeyName.GEN_DEFAULT_FIELD, expDefaultFields);
		paramMap.put(ParamKeyName.IS_LOGIC_DELETE, expLogicDelete);
		
		String init = request.getParameter("init");
		String version = request.getParameter("version");
		paramMap.put(ParamKeyName.PAGE_INIT_STRUCTURE, Boolean.valueOf(init));
		paramMap.put(ParamKeyName.PAGE_VERSION, version);
		paramMap.put(ParamKeyName.MODULE_ID, moduleIDs[0]);
		
		
		if(requestPrefix != null) {
			if(!requestPrefix.startsWith("/")) {
				requestPrefix = "/" + requestPrefix;
			}
			if(requestPrefix.endsWith("/")) {
				requestPrefix = requestPrefix.substring(0,requestPrefix.length()-1);
			}
			paramMap.put(ParamKeyName.REQUEST_PREFIX, requestPrefix);
		}
		
		moduleService.codeGenerate(packageName,moduleIDs,file,new AuthorInfo(user.getUserID(),user.getAuthorName()),defaultGroup,paramMap);
	}
	

	private User getUser(HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute(User.USER_KEY_NAME);
		if(user == null) {
			throw new RuntimeException("用户未登录或登录超时");
		}
		return user;
	}
	
	public String fileNameEncoding(String fileName, HttpServletRequest request)
			throws IOException {
		String agent = request.getHeader("User-Agent");
		if (agent.contains("Firefox")) {
			fileName = "=?utf-8?B?"
					+ Base64.encodeBase64String(fileName.getBytes("utf-8")) + "?=";
		} else {
			fileName = URLEncoder.encode(fileName, "utf-8");
		}
		return fileName;
	}
	
	private void makeZip(File sourceFile,OutputStream out) throws Exception {
		ArchiveOutputStream gzippedOut = new ArchiveStreamFactory()
			    .createArchiveOutputStream("zip", out);
		
		zipSubFiles(sourceFile,gzippedOut,"");
		
		gzippedOut.close();
	}
	
	private static void zipSubFiles(File sourceFile,ArchiveOutputStream gzippedOut,String path) throws Exception {
		File[] listFiles = sourceFile.listFiles();
		for (File f : listFiles) {
			String entryPath = path + f.getName();
	        ArchiveEntry entry = gzippedOut.createArchiveEntry(f, entryPath);
	        gzippedOut.putArchiveEntry(entry);
	        if (f.isFile()) {
	            try (InputStream i = Files.newInputStream(f.toPath())) {
	                IOUtils.copy(i, gzippedOut);
	            }
	            gzippedOut.closeArchiveEntry();
	        }else {
	        	gzippedOut.closeArchiveEntry();
	        	zipSubFiles(f,gzippedOut,entryPath + "/");
	        }
	    }
	}
	
		private void delete(File f) {
		File[] listFiles = f.listFiles();
		for (int i = 0; i < listFiles.length; i++) {
			if(listFiles[i].isDirectory()) {
				if(listFiles[i].list().length == 0) {
					listFiles[i].delete();
				}else {
					delete(listFiles[i]);
					listFiles[i].delete();
				}
			}else{
				listFiles[i].delete();
			}
			
		}
	}
	
}
